function [U_k,W_k,J_k,delta_k,iter] = inner_loop(s_star,m_star,Gdest_0,lambda_0,delta_k,alpha,ksi,cs,cu,sigma,g_euler,S_obs,M,beta)
%This function computes average payoff delta and ballast probabilities ccp that implements 
% q_star = m_star*Gdest_0 and s_star

diff_m = 10;
Niter_m = 10000;
iter = 1;
eps = exp(-3);

while diff_m>eps && iter<Niter_m
    %
    % Given a average payoff delta_k, compute the ships' choice probabilities
    %
    [U_k,W_k,J_k] = fixedpointU_monopolist(cs,cu,sigma,M,beta,ksi,g_euler,Gdest_0,delta_k,lambda_0);
    ccp_k = ccp_equil(W_k,M);

    %
    % Given ccp_k, compute the spatial distribution of ships
    %
    
    it = 0;
    diff_s = 10;
    q0 = m_star.*Gdest_0./ksi;
    b0 = (s_star - m_star).*ccp_k./ksi;
    tt = (sum(b0(:))+nansum(q0(:)));
    q0 = q0./tt;
    b0 = b0./tt;
    
    while diff_s>exp(-3)
        s_arrive = (sum(ksi.*b0,1)' + nansum(ksi.*q0,1)');
        b1 = b0.*(1-ksi) +  s_arrive.*(1-lambda_0).*ccp_k;
        q1 = q0.*(1-ksi) +  s_arrive.*(lambda_0).*Gdest_0;
        diff_s = 10^3.*S_obs.*max(max(abs(b1(:)-b0(:))),max(abs(q1(:)-q0(:))));
        b0 = b1;
        q0 = q1;
        it = it + 1;
    end
    %
    % update the guess for delta and check the convergence
    %
    s_k = S_obs.*(nansum(ksi.*q0,1)' + sum(ksi.*b0,1)')*10^3;
    delta = delta_k + alpha*(s_star -s_k);
    diff_m = max(abs(s_star-s_k)./s_star);
    
    delta_k = delta;
    iter = iter+1;
    
end

end

